﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.PresentationFramework.Screens;
using System.Collections;
using XWord.Fundamental.Domain;
using System.Reflection;
using XWord.Fundamental.Data.Repositories;
using XWord.Fundamental.Data.Impl;
using System.Windows;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.ComponentModel;
using System.IO;
using Caliburn.Core.IoC;
using Microsoft.Practices.ServiceLocation;
using Caliburn.PresentationFramework.ApplicationModel;
using System.Xml;
using System.Net;
using Iesi.Collections;
namespace XWord.GUI.Presenters
{
    public interface IWordPresenter : IScreen
    {
    }

     [Singleton(typeof(IWordPresenter))]
    public class WordPresenter : ScreenConductor<IScreen>, IWordPresenter
    {
        private readonly IWordRepository _wordRepository;
        private readonly ICategoryRepository _categoryRepository;
        private readonly EtymaRepository _etymaRepository;

        public WordPresenter()
        {
            
            _wordRepository = new WordRepository();
            _categoryRepository = new CategoryRepository();
            _etymaRepository = new EtymaRepository();
            WordList = new ObservableCollection<Word>(_wordRepository.LoadWordList());
            CategoryList = new ObservableCollection<Category>(_categoryRepository.GetAll());
            EtymaList = new ObservableCollection<Etymon>(_etymaRepository.GetEtymaList<Etymon>());
            SuffixList = new ObservableCollection<Suffix>(_etymaRepository.GetEtymaList<Suffix>());
            UnKnownWordCount = _wordRepository.GetUnKnownWordCount();
        }

        public IList<Word> WordList { get; set; }

        public IList<Category> CategoryList { get; set; }

        public IList<Etymon> EtymaList { get; set; }

        public IList<Suffix> SuffixList { get; set; }

        public int UnKnownWordCount { get; set; }

        public void MarkIsIgnore(IList selectedWord)
        {
            //UnitOfWork.CurrentSession.Clear();
            MarkProperty(selectedWord, "IsIgnore");
        }

        public void IgnoreWord(IList selectedWord)
        {
          
            foreach (var item in selectedWord)
            {
                var word = item as Word;

                word.IsIgnore = true;
                _wordRepository.SaveWord(word);
            }
        }

        public void MarkIsIgnore(Word selectedWord)
        {
            //UnitOfWork.CurrentSession.Clear();
            var list = new List<Word>();
            list.Add(selectedWord);
            MarkProperty(list, "IsIgnore");
        }

        public void MarkIsShortRead(IList selectedWord)
        {
            MarkProperty(selectedWord, "IsShortRead");
        }

        public void MarkIsExpert(IList selectedWord)
        {
            MarkProperty(selectedWord, "IsExpert");
        }

        public void MarkIsFamiliar(IList selectedWord)
        {
            MarkProperty(selectedWord, "IsFamiliar");
        }

        private void MarkProperty(IList selectedWord,string propertyName)
        {
            foreach (object item in selectedWord)
            {
                var currentProperty = item.GetType().GetProperty(propertyName);
                var currentVal=Convert.ToBoolean(currentProperty.GetValue(item,null));
                currentProperty.SetValue(item, !currentVal, null);
                //UnitOfWork.CurrentSession.Update(item);
               // UnitOfWork.CurrentSession.Flush();
               // _wordRepository.SaveWord(item as Word);
            }
            ICollectionView collectionView = CollectionViewSource.GetDefaultView(WordList);
            collectionView.Refresh();
          //  MessageBox.Show("成功");
        }

        public void SaveWordSuffixComment(IList selectedWord)
        {

        }

        public void ReflashWordList()
        {
            WordList.Clear();
            foreach (var item in _wordRepository.GetAll())
            {
                WordList.Add(item);
            }
          //  WordList = new ObservableCollection<Word>(_wordRepository.GetAll());
        }

        public void SimpleWordSearch(string text)
        {
            ICollectionView collectionView = CollectionViewSource.GetDefaultView(WordList);
            collectionView.Filter = new Predicate<object>((obj) =>
            {
                var entity = obj as Word;
                return entity.Name.StartsWith(text);
            });
        }

        public void ShortReadWordSearch()
        {
        }


        public void FilterCategoryWord(Category category)
        {
            if (category == null) return;
            var query = category.Words;

            ICollectionView collectionView = CollectionViewSource.GetDefaultView(WordList);
            collectionView.Filter = new Predicate<object>((obj) =>
            {
                var entity = obj as Word;
                return query.Contains(entity);
            });
        }

        public void FilterSuffixWord(Suffix suffix)
        {
            ICollectionView collectionView=CollectionViewSource.GetDefaultView(WordList);
            collectionView.Filter = new Predicate<object>((obj) =>
            {
                var entity = obj as Word;
                return entity.Name.EndsWith(suffix.Name);
            });
        }

        public void ImportWordList()
        {
            UnitOfWork.CurrentSession.Clear();
            string line = string.Empty;
            using (TextReader streamReader =
                new StreamReader("D://develop//wpf//WordAssistant//WordAssistantApp//word3.txt", System.Text.Encoding.GetEncoding("GB2312")))
            {
                while ((line = streamReader.ReadLine()) != null)
                {
                    int ignore = line.IndexOf(" ");
                    if (true)
                    {
                        //.Substring(0, ignore).ToLower()
                        string name = line.ToLower().Trim();
                        if (WordList.Any(ee => ee.Name.Trim() == name))
                        {
                            //return;
                            //Word word = WordList.First(ee => ee.Name.Trim() == name);
                            //word.Comment = line.ToLower().Substring(ignore).Trim();
                        }
                        else
                        {
                            Word newword = new Word();
                            newword.Name = name;
                            newword.Suffix = string.Empty;
                            newword.Sentences = new HashedSet();
                            var dd = NetWord.aa(newword.Name, newword);
                            if (!string.IsNullOrEmpty(dd["def"].ToString()))
                            {
                                newword.Comment = dd["def"].ToString();
                                newword.Audio = dd["audio"].ToString();
                                newword.Pron = dd["pron"].ToString();
                                newword.WordIndex = 0;
                                newword.Sentences.AddAll(dd["sentence"] as ICollection);
                                UnitOfWork.CurrentSession.Save(newword);
                                UnitOfWork.CurrentSession.Flush();
                                //_wordRepository.SaveWord(newword);
                                WordList.Add(newword);
                            }
                        }
                    }
                }
            }
        }

        public void ImportEtymonList()
        {
            UnitOfWork.CurrentSession.Clear();
            string line = string.Empty;


            using (TextReader streamReader =
                new StreamReader("D://develop//wpf//WordAssistant//WordAssistantApp//word4.txt", System.Text.Encoding.GetEncoding("GB2312")))
            {
                while ((line = streamReader.ReadLine()) != null)
                {
                    int ignore = line.IndexOf(" ");
                    if (ignore > 0)
                    {
                        string name = line.ToLower().Substring(0, ignore).ToLower().Trim();
                        
                        if (WordList.Any(ee => ee.Name.Trim() == name))
                        {
                            Word word = WordList.First(ee => ee.Name.Trim() == name);
                            word.Suffix = line.ToLower().Substring(ignore).Trim();
                            _wordRepository.SaveWord(word);
                        }
                    }
                }
            }
        }

        public void OpenWordSearchDialog()
        {
            var presenter = ServiceLocator.Current.GetInstance<WordFinderPresenter>();
            
            ServiceLocator.Current.GetInstance<IWindowManager>()
                .Show(presenter, null, ExecuteShutdownModel);
            presenter.WordItems = this.WordList;
        }

        public void OpenCategoryDialog(Category category)
        {
            var presenter = ServiceLocator.Current.GetInstance<CategoryEditPresenter>();
            presenter.Detail = category;
            presenter.CategoryList = CategoryList;
            ServiceLocator.Current.GetInstance<IWindowManager>()
                .Show(presenter, null, ExecuteShutdownModel);
            
        }

        public void OpenEtymaLibraryDialog()
        {
            //var presenter = ServiceLocator.Current.GetInstance<WordFinderPresenter>();

            //ServiceLocator.Current.GetInstance<IWindowManager>()
            //    .Show(presenter, null, ExecuteShutdownModel);
            //presenter.WordItems = this.WordList;
        }

        public void OpenRCArticleDialog()
        {
            var presenter = ServiceLocator.Current.GetInstance<RCArticlePresenter>();

            ServiceLocator.Current.GetInstance<IWindowManager>()
                .Show(presenter, null, ExecuteShutdownModel);
            //presenter.WordItems = this.WordList;
        }

        public void AssociateCategoryWord(Category category, IList selectedWord)
        {
            //category.Words.Clear();
            category.Words.AddAll(selectedWord);
            _categoryRepository.SaveCategory(category);
        }

        public void UnAssociateCategoryWord(Category category, IList selectedWord)
        {
            //category.Words.Clear();
            category.Words.RemoveAll(selectedWord);
            _categoryRepository.SaveCategory(category);
        }

        public void DeleteWord(IList selectedWord)
        {
            foreach (var item in selectedWord)
            {
                _wordRepository.DeleteWord(item as Word);
                
            }
            for (int i = 0; i < selectedWord.Count; i++)
            {
                WordList.Remove(selectedWord[i] as Word);
            }
            
        }
         

        public void DeleteCategory(Category category)
        {
            _categoryRepository.DeleteCategory(category);

            CategoryList.Remove(category);

        }
        public void CopySelectedWord()
        {
        }

        public void ChangeSuffix(IList selectedWord)
        {
            
            foreach (var item in selectedWord)
            {
                var word = item as Word;
                var saveword = UnitOfWork.CurrentSession.Get<Word>(word.Id);
                saveword.Suffix = saveword.Suffix;
                UnitOfWork.CurrentSession.Save(saveword);
                UnitOfWork.CurrentSession.Flush();
                //word.IsIgnore = true;
               // _wordRepository.SaveWord(word);
            }

        }
    }

    public class NetWord
    {
        public static Dictionary<string, object> aa(string word,XWord.Fundamental.Domain.Word entity)
        {
            var dic = new Dictionary<string, object>();
            string a = string.Empty;
            dic["def"] = string.Empty;
            dic["audio"] = string.Empty;
            dic["pron"] = string.Empty;
            var list = new List<Sentence>();
            dic["sentence"] = list;
            WebRequest request = WebRequest.Create(string.Format("http://dict.cn/ws.php?utf8=true&q={0}",word));
            
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream,Encoding.UTF8);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            if (!responseFromServer.Contains("Not Found"))
            {
                XmlDocument doc = new XmlDocument();
                doc.InnerXml = responseFromServer;
               // doc.g
                // Display the content.
                var node = doc.DocumentElement.SelectNodes("descendant::def");
                if (node.Count > 0)
                {
                    dic["def"] = node[0].InnerText;
                    a = node[0].InnerText;
                    Console.WriteLine(word+"  " +a);
                }
                var audionode = doc.DocumentElement.SelectNodes("descendant::audio");
                if (audionode.Count > 0)
                {
                    dic["audio"] = audionode[0].InnerText;
                   
                }
                var pronnode = doc.DocumentElement.SelectNodes("descendant::pron");
                if (pronnode.Count > 0)
                {
                    dic["pron"] = pronnode[0].InnerText;

                }
                var sentnode = doc.DocumentElement.SelectNodes("descendant::sent");
                
                if (sentnode.Count > 0)
                {
                   //System.Xml.x

                    if (entity.Sentences.Count == 0)
                    {
                        foreach (var item in sentnode)
                        {
                            XmlNode current = item as XmlNode;
                            Sentence sentence = new Sentence();

                            sentence.Origin = current.SelectNodes("orig")[0].InnerText;
                            sentence.Translate = current.SelectNodes("trans")[0].InnerText;
                            UnitOfWork.CurrentSession.Persist(sentence);
                            list.Add(sentence);

                            // item as XmlElement
                        }
                    }
                    
                }
            }
            else
            {
                Console.WriteLine(word + "/Not Found");
            }
            
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
            return dic;
           
        }
    }
}
